<?php
/**
 * Description:
 *
 * @author      Eden
 * @datetime    2016/12/27 20:36
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

use Wechat\Loader;

class Detail extends WX_Controller
{
    // 基地ID
    private $goodsId = 0;
    private $userId = 0;
    private $width = 640;
    private $height = 360;

    /**
     * 初始化
     * @throws Exception
     */
    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        // 放入缓存
        $this->load->view('wx/goods/detail.html');
    }

    /**
     * 商品详情
     * @return bool
     */
    public function getGoodsDetail()
    {

        $this->goodsId = (int) $this->input->get('goodsId');

        $db = clone($this->db);
        $q = $db->select('g.goodsName, g.description, g.baseId, bc.name as categoryName, b.name as baseName, g.thumb,
            g.bannerThumb, g.streamId, g.content, g.pv, g.likes,
            g.stars, g.comments, g.price, g.stock, g.unit, g.expressWeight, g.created, g.status')
            ->from('base_goods as g')
            ->join('base as b', 'b.id = g.baseId')
            ->join('base_category as bc', 'bc.id = g.categoryId')
            ->where('g.status = 1')
            ->where('g.id', $this->goodsId)
            ->get();
        $row = $q->row_array();

        if (empty($row)) {
            return false;
        }

        $thumb = !empty($row['bannerThumb']) ? $row['bannerThumb'] : $row['thumb'];
        $row['goodsId'] = $this->goodsId;
        $row['baseId'] = intval($row['baseId']);
        $row['thumb'] = thumb($thumb, $this->width, $this->height);
        $row['pv'] = intval($row['pv']);
        $row['likes'] = intval($row['likes']);
        $row['stock'] = intval($row['stock']);
        $row['stars'] = intval($row['stars']);
        $row['price'] = doubleval(money_format('%i', $row['price']));
        $row['expressWeight'] = doubleval($row['expressWeight']);
        $row['created'] = formateTimeStamp($row['created']);
        $row['content'] = $row['content'];
        $row['status'] = $row['status'] == 1 ? 'onSale' : 'offSale';
        $row['isCollected'] = $this->checkCollected();
        $row['live'] = array(
            'status' => false,
            'data' => []
        );
        $row['comments'] = array(
            'total' => intval($row['comments']),
            'data' => $this->_get2Comments()
        );
        $row['related'] = $this->_getRelatedGoods();

        if (!empty($row['streamId'])) {
            $stream = $this->_getStreamUrl($row['streamId']);
            if (!empty($stream) && $stream['status'] == 1) {
                $row['live'] = array(
                    'status' => true,
                    'address' => array(
                        'hd' => value($stream, 'videoUrlHD'),
                        'sd' => value($stream, 'videoUrlSD')
                    )
                );
            }
        }
        unset($row['streamId']);

        $send['state'] = true;
        $send['data'] = $row;
        $this->output->send($send);
    }

    /**
     * 直播
     * @param int $streamId
     * @return mixed
     */
    protected function _getStreamUrl($streamId = 0)
    {
        $db = clone($this->db);
        $q = $db->select('videoUrlHD, videoUrlSD, status')->get_where('stream_device', array('id' => $streamId));
        return $q->row_array();
    }

    /**
     * 检查用户是否收藏
     * @return bool
     */
    private function checkCollected()
    {
        if (empty($this->userId)) {
            return false;
        }
        $db = clone($this->db);
        $q = $db->get_where('user_collect', array('userId' => $this->userId, 'goodsId' => $this->goodsId));
        if ($q->row_array()) {
            return true;
        }
        return false;
    }

    /**
     * 相关产品
     * @return array
     */
    private function _getRelatedGoods()
    {
        $detail= array(
            'total' => 0,
            'data' => []
        );
        $db = clone($this->db);
        $q = $db->select('id, goodsName, thumb, recommendThumb, streamId, price, stock, created')
            ->from('base_goods')
            ->order_by('pv', 'DESC')
            ->limit(8)
            ->where(array('status' => 1))
            ->where('stock > 0')
            ->get();
        $rows = $q->result_array();
        if (empty($rows)){
            return $detail;
        }

        $results = $this->_doAfterSelectGoods($rows);
        $detail['total'] = count($results);
        $detail['data'] = $results;
        return $detail;
    }

    /**
     * 处理返回结果
     * @param array $goods
     * @return array
     */
    private function _doAfterSelectGoods($goods = array())
    {
        $results = [];
        foreach($goods as $item) {
            $thumb = !empty($item['recommendThumb']) ? $item['recommendThumb'] : $item['thumb'];
            $results[] = array(
                'goodsId' => intval($item['id']),
                'goodsName' => value($item, 'goodsName'),
                'thumb' => thumb($thumb, $this->width, $this->height),
                'stock' => intval($item['stock']),
                'price' => money_format('%i', $item['price']),
                'created' => formateTimeStamp($item['created']),
                'isLive' => !empty($item['streamId'])
            );
        }
        return $results;
    }

    /**
     * 获取两条最新的留言
     * @return array
     */
    private function _get2Comments()
    {
        $db = clone($this->db);
        $q = $db->select('c.content, c.created, u.nickName, up.avatar')
            ->where(array('c.status' => 1, 'c.goodsId' => $this->goodsId))
            ->limit(2)
            ->join('user as u', 'u.id = c.userId')
            ->from('base_goods_comments as c')
            ->order_by('c.created', 'DESC')
            ->join('user_profile as up', 'up.userId = c.userId')
            ->get();

        $rows = $q->result_array();
        if (empty($rows)) {
            return [];
        }

        foreach($rows as &$item) {
            $item['avatar'] = thumb($item['avatar'], 100, 100);
            $item['created'] = formateTimeStamp($item['created']);
        }

        return $rows;
    }
}
